package br.urca.interceptor;

import java.text.Normalizer;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Accepts;
import br.com.caelum.vraptor.AroundCall;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.controller.ControllerMethod;
import br.com.caelum.vraptor.interceptor.SimpleInterceptorStack;
import br.urca.controller.ValidacaoDocumentosController;

@Intercepts
public class ValidacaoInterceptor {
	
	private String metodo;
	
	private Result result;
	private HttpServletRequest request;
	
	@Deprecated public ValidacaoInterceptor() { }
	
	@Inject
	public ValidacaoInterceptor(Result result, HttpServletRequest request) {
		super();
		this.result = result;
		this.request = request;
	}
	
	@Accepts
	public boolean accepts(ControllerMethod method) {
		setMetodo(method.getMethod().getName());
		return method.getController().getType().equals(ValidacaoDocumentosController.class);
	}
	
	@AroundCall
	public void valida(SimpleInterceptorStack stack) {
		if (getMetodo().trim().equalsIgnoreCase("validate")) {
			String md5 = request.getParameter("md5");
			md5 = removeCaracteresEspeciais(md5);
			if (urlValida(md5)) {
				stack.next();
			} else {
				result
					.include("mensagem", "Atenção! Documento não encontrado!")
					.redirectTo(ValidacaoDocumentosController.class).index();
			}
		} else if (getMetodo().trim().equalsIgnoreCase("validar")) {
			stack.next();
		}
	}
	
	private boolean urlValida(String parametro) {
		try {
			return (parametro.length() > 30 && parametro.length() < 33 );
		} catch (Exception e) {
			return false;
		}
	}

	private String removeCaracteresEspeciais(String text) {
		String retorno = text;
		try {
			retorno = Normalizer.normalize(retorno, Normalizer.Form.NFD);
			retorno = retorno.replaceAll("[^\\p{ASCII}]", "");
			retorno = retorno.replaceAll("-", "");
			System.out.println(retorno);
		} catch (Exception e) {
			retorno = "";
		}
		return retorno;
	}

	public String getMetodo() {
		return metodo;
	}

	public void setMetodo(String metodo) {
		this.metodo = metodo;
	}

}
